package com.mazaiting.instructions.conversions;

import com.mazaiting.instructions.base.NoOperandsInstruction;
import com.mazaiting.rtda.MtFrame;
import com.mazaiting.rtda.MtOperandStack;

/**
 * i2x系列指令把int变量强制转换成其他类型
 *
 * @author mazaiting
 * @since 2021/8/15
 */
public class I2xInstruction {

    /**
     * 整型转换为字节
     */
    public static class I2B extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            int v1 = stack.popInt();
            byte v2 = (byte)v1;
            stack.pushInt(v2);
        }
    }

    /**
     * 整型转换为字符
     */
    public static class I2C extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            int v1 = stack.popInt();
            char v2 = (char)v1;
            stack.pushInt(v2);
        }
    }

    /**
     * 整型转换为短整型
     */
    public static class I2S extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            int v1 = stack.popInt();
            short v2 = (short)v1;
            stack.pushInt(v2);
        }
    }

    /**
     * 整型转换为单精度类型
     */
    public static class I2F extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            int v1 = stack.popInt();
            float v2 = (float)v1;
            stack.pushFloat(v2);
        }
    }

    /**
     * 整型转换为双精度
     */
    public static class I2D extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            stack.pushDouble(stack.popInt());
        }
    }

    /**
     * 整型转换为长整型
     */
    public static class I2L extends NoOperandsInstruction {
        @Override
        public void execute(MtFrame frame) {
            MtOperandStack stack = frame.getOperandStack();
            stack.pushLong(stack.popInt());
        }
    }
}
